package com.one.common.utils.map;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.one.common.utils.Logger;
import com.one.common.utils.Toaster;

import java.io.File;
import java.net.URISyntaxException;

/**
 * Author: zhulunjun
 * Email: zhulunjun@qq.com
 * CreateDate: 2019/11/7 16:51
 * Description：选择导航
 **/
public class SelecteMapUtils implements LocationUtils.OnLocationListener{

    private Context mContext;
    private String endLa,endLo,endAddress,endCity;

    public SelecteMapUtils(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 去第三方地图
     * @param la 终点经纬度
     * @param lo 终点经纬度
     * @param addressName 终点详细地址
     */
    public void toMap(String la, String lo, String addressName, String city){
        this.endAddress = addressName;
        this.endLa = la;
        this.endLo = lo;
        this.endCity = city;

        LocationUtils.geocodeSearch(mContext, addressName, city, new LocationUtils.onGeocodeSearchedListener() {
            @Override
            public void onGeocodeSearched(GeocodeAddress result) {
                endLa = result.getLatLonPoint().getLatitude()+"";
                endLo = result.getLatLonPoint().getLongitude()+"";
                endAddress = result.getFormatAddress();
                LocationUtils.location(mContext, SelecteMapUtils.this);
            }

            @Override
            public void onGeocodeSearchedFail() {
                Toaster.showLongToast("位置信息获取失败");
            }
        });

    }

    /**
     * 导航
     * 1. 高德是否安装
     * 2. 百度是否安装
     * 3. 百度网页版
     */
    private void selectMap(String sla, String slo, String la, String lo, String addressName){
        if(isInstallByRead("com.autonavi.minimap")){
            setUpGaodeAppByMine(sla,slo,la,lo,addressName);
        }else if(isInstallByRead("com.baidu.BaiduMap")){
            setUpBaiduAPPByMine(sla,slo,la,lo,addressName);
        }else {
            webByMine(sla,slo,la,lo,addressName);
        }
    }

    /**
     * 我的位置到终点通过百度地图
     */
    void setUpBaiduAPPByMine(String sla, String slo, String la, String lo, String addressName) {
        try {
            //("baidumap://map/direction?region=beijing&origin=39.98871,116.43234&destination=name:西直门&mode=driving")

            Intent intent = Intent.getIntent("intent://map/direction?" +
                    "origin=我的位置&" +
                    "destination=" + addressName + "&" +
                    "mode=driving&" +
                    "src=yourCompanyName|yourAppName#Intent;" +
                    "scheme=bdapp;" +
                    "package=com.baidu.BaiduMap;end");
//            Intent intent = new Intent();
//            intent.setData(Uri.parse("baidumap://map/direction?" +
//                    "origin=我的位置&" +
//                    "destination=latlng:"+
//                    endLa+","+
//                    endLon+"&" +
//                    "mode=driving"));
//            intent.setPackage("com.baidu.BaiduMap");
            if (isInstallByRead("com.baidu.BaiduMap")) {
                mContext.startActivity(intent);
                Logger.d("百度地图客户端已经安装");
            } else {
                Logger.d("没有安装百度地图客户端");
                webByMine(sla, slo, la,lo,addressName);

            }
        } catch (Exception e) {
            e.printStackTrace();
            Logger.d("百度地图 "+e.getMessage());
            webByMine(sla, slo, la,lo,addressName);
        }
    }

    /**
     * 我的位置BY高德
     */
    void setUpGaodeAppByMine(String sla, String slo, String la, String lo, String addressName) {
        try {
            Intent intent = Intent.getIntent("androidamap://route?" +
                    "sourceApplication=softname&" +
                    "sname=我的位置&" +
                    "dlat=" + la + "&" +
                    "dlon=" + lo + "&" +
                    "dname=" + addressName + "&" +
                    "dev=0&m=0&t=0"); // t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
            if (isInstallByRead("com.autonavi.minimap")) {
                mContext.startActivity(intent);
                Logger.d("高德地图客户端已经安装");
            } else {
                webByMine(sla, slo, la,lo,addressName);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            webByMine(sla, slo, la,lo,addressName);
        }
    }

    /**
     * 百度地图定位
     * http://lbsyun.baidu.com/index.php?title=uri/api/web
     * http://api.map.baidu.com/direction?origin=latlng:34.264642646862,108.95108518068|name:我家&destination=大雁塔&mode=driving&region=西安&output=html&src=webapp.baidu.openAPIdemo
     * //调起百度PC或Web地图，展示"西安市"从（lat:34.264642646862,lng:108.95108518068 ）"我家"到"大雁塔"的驾车路线。
     */
    private void webByMine(String sla, String slo, String la, String lo, String addressName){
        String url = "http://api.map.baidu.com/direction?origin=latlng:"+sla+","+slo+"|name:我的位置&destination=latlng:"+la+","+lo+"|name:"+addressName+"&mode=driving&region="+endCity+"&coord_type=gcj02&output=html&src="+mContext.getPackageName();
        Logger.d("调起百度地图Web "+url);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        mContext.startActivity(intent);
    }

    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByRead(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    @Override
    public void onLocated(AMapLocation aMapLocation) {
        selectMap(aMapLocation.getLatitude()+"", aMapLocation.getLongitude()+"", endLa,endLo,endAddress);
    }

    @Override
    public void onLocationPermissionfaild() {
        Toaster.showLongToast("定位失败，请稍后重试");
    }
}
